#pragma once
#include "socket.hpp"

#include <iostream>
#include <pthread.h>

class TcpServer
{
private:
	TcpServer(uint16_t port) : _port(port)
	{
	}
	uint16_t _port;
	static TcpServer *_tcp_ptr;
	Socket _listenSock;

	void init()
	{
		_listenSock.init();		 // socket
		_listenSock.Bind(_port); // bind
		_listenSock.Listen();	 // listen
		lg(NOTICE, "listen success fd:%d", _listenSock.getSock());
	}

public:
	static TcpServer *getTcpServer(uint16_t port)
	{
		static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
		if (_tcp_ptr == nullptr)
		{
			pthread_mutex_lock(&mtx);
			if (_tcp_ptr == nullptr)
			{
				_tcp_ptr = new TcpServer(port); // 构造
				_tcp_ptr->init();				// 初始化socket
			}
			pthread_mutex_unlock(&mtx);
		}
		return _tcp_ptr;
	}

	Socket *getListenSock()
	{
		return &_listenSock;
	}
};
TcpServer *TcpServer::_tcp_ptr = nullptr;
